package handler


import (
	"golang.org/x/net/context"
	oauth2 "git.oschina.net/fanbuchi/xgggh/oauth2/proto/oauth2"
	srv "git.oschina.net/fanbuchi/xgggh/oauth2/service"
	 "git.oschina.net/fanbuchi/xgggh/errs"
	"git.oschina.net/fanbuchi/xgggh/oauth2/service"
	"git.oschina.net/fanbuchi/xgggh/oauth2/model"
	"git.oschina.net/fanbuchi/xgggh/oauth2/tokentypes"
)
//SELECT client_id, expires_at, token, user_id,scope FROM oauth2.refresh_tokens;

func refreshToken(ctx context.Context, req *oauth2.TokenReq, rsp *oauth2.TokenRsp)error {
	//checklist
	if req.ClientId=="" {
		return errs.ClientNotFound
	}
	if req.ClientSecret=="" {
		return errs.ClientSecretNotFound
	}

	_client,err:=service.ClientSearchByClientId(req.ClientId)
	if err !=nil{
		return err
	}
	//key|secret 非法
	if _client==nil||_client.Secret!=req.ClientSecret {
		return errs.ClientInvalid
	}

	refreshToken,err:= srv.GetValidRefreshToken(req.RefreshToken,_client)
	//refreshTokenScope,err:= service.GetRefreshTokenScope(&refreshToken,nil)
	if err !=nil{
		return err
	}
	_account:=model.Account{}
	_account.ID=refreshToken.AccountId

	accessToken, refreshToken, err := srv.UserLogon(_client,
		&_account,
		refreshToken.Scope)
	if err != nil {
		return  err
	}

	// Create response
	rsp.Data=&oauth2.Token{AccountId:int64(accessToken.AccountId),
		AccessToken:accessToken.Token,
		ExpiresIn:model.GetOauthConfig().AccessTokenLifetime,
		TokenType:tokentypes.Bearer,
		RefreshToken:refreshToken.Token,
		Scope:accessToken.Scope,
	}

	return err
}
